import sqlite3
from datetime import datetime, timedelta

def init_database():
    conn = sqlite3.connect('campus_food.db')
    
    # 创建表
    conn.execute('''
    CREATE TABLE IF NOT EXISTS canteens (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        location TEXT NOT NULL,
        type TEXT NOT NULL,
        description TEXT,
        avg_price INTEGER,
        score REAL DEFAULT 0
    )
    ''')
    
    conn.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL
    )
    ''')
    
    conn.execute('''
    CREATE TABLE IF NOT EXISTS reviews (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER NOT NULL,
        canteen_id INTEGER NOT NULL,
        rating INTEGER NOT NULL,
        content TEXT NOT NULL,
        created_at TEXT NOT NULL,
        FOREIGN KEY (user_id) REFERENCES users (id),
        FOREIGN KEY (canteen_id) REFERENCES canteens (id)
    )
    ''')
    
    # 插入测试数据
    canteens_data = [
        ('麻辣香锅', '一食堂', '川菜', '香辣可口，配料丰富', 25, 4.5),
        ('牛肉面', '二食堂', '面食', '汤头鲜美，面条劲道', 15, 4.2),
        ('奶茶店', '三食堂', '饮品', '多种口味，甜度可选', 12, 4.6),
        ('黄焖鸡米饭', '一食堂', '快餐', '鸡肉鲜嫩，米饭管饱', 20, 4.3),
        ('饺子馆', '二食堂', '面食', '手工制作，馅料多样', 18, 4.4),
        ('炸鸡店', '三食堂', '快餐', '外酥里嫩，多种酱料', 22, 4.1)
    ]
    
    for canteen in canteens_data:
        conn.execute(
            'INSERT INTO canteens (name, location, type, description, avg_price, score) VALUES (?, ?, ?, ?, ?, ?)',
            canteen
        )
    
    # 测试用户
    users_data = [
        ('student1', '123456'),
        ('student2', '123456'),
        ('test', '123456')
    ]
    
    for user in users_data:
        conn.execute(
            'INSERT OR IGNORE INTO users (username, password) VALUES (?, ?)',
            user
        )
    
    # 测试评价
    reviews_data = [
        (1, 1, 5, '味道非常棒，强烈推荐！', datetime.now() - timedelta(days=2)),
        (2, 1, 4, '有点辣但是很好吃', datetime.now() - timedelta(days=1)),
        (1, 2, 5, '牛肉很入味，汤很好喝', datetime.now() - timedelta(days=3)),
        (3, 2, 4, '面条口感不错', datetime.now() - timedelta(days=1))
    ]
    
    for review in reviews_data:
        conn.execute(
            'INSERT INTO reviews (user_id, canteen_id, rating, content, created_at) VALUES (?, ?, ?, ?, ?)',
            review
        )
    
    conn.commit()
    conn.close()
    print("数据库初始化完成！")
    print("测试账号: student1/123456, student2/123456, test/123456")

if __name__ == '__main__':
    init_database()